#!/bin/bash

# PowerBank系统 - Nacos服务注册中心部署脚本
# 版本: 1.0.0
# 日期: 2025-01-07

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 配置变量
NACOS_VERSION="2.2.0"
NACOS_HOME="/opt/nacos"
NACOS_USER="nacos"
MYSQL_HOST="localhost"
MYSQL_PORT="3306"
MYSQL_DB="nacos"
MYSQL_USER="nacos"
MYSQL_PASSWORD="nacos123"

echo -e "${GREEN}=== PowerBank Nacos 部署脚本 ===${NC}"

# 检查是否为root用户
if [[ $EUID -eq 0 ]]; then
   echo -e "${RED}请不要使用root用户运行此脚本${NC}"
   exit 1
fi

# 函数：打印信息
print_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 函数：检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        print_error "$1 命令未找到，请先安装"
        exit 1
    fi
}

# 函数：检查Java环境
check_java() {
    print_info "检查Java环境..."
    if ! command -v java &> /dev/null; then
        print_error "Java未安装，请先安装JDK 17+"
        exit 1
    fi
    
    JAVA_VERSION=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}' | awk -F. '{print $1}')
    if [ "$JAVA_VERSION" -lt 17 ]; then
        print_error "需要JDK 17或更高版本，当前版本: $JAVA_VERSION"
        exit 1
    fi
    
    print_info "Java环境检查通过: $(java -version 2>&1 | head -n 1)"
}

# 函数：下载Nacos
download_nacos() {
    print_info "下载Nacos $NACOS_VERSION..."
    
    cd /tmp
    NACOS_FILE="nacos-server-${NACOS_VERSION}.tar.gz"
    
    if [ ! -f "$NACOS_FILE" ]; then
        print_info "正在下载 $NACOS_FILE ..."
        wget "https://github.com/alibaba/nacos/releases/download/${NACOS_VERSION}/${NACOS_FILE}" || {
            print_error "下载失败，请检查网络连接"
            exit 1
        }
    else
        print_info "文件已存在，跳过下载"
    fi
}

# 函数：安装Nacos
install_nacos() {
    print_info "安装Nacos到 $NACOS_HOME ..."
    
    # 创建安装目录
    sudo mkdir -p $NACOS_HOME
    sudo chown $USER:$USER $NACOS_HOME
    
    # 解压
    cd /tmp
    tar -zxf nacos-server-${NACOS_VERSION}.tar.gz
    cp -r nacos/* $NACOS_HOME/
    
    print_info "Nacos安装完成"
}

# 函数：配置数据库
setup_database() {
    print_info "配置Nacos数据库..."
    
    # 检查MySQL是否运行
    if ! systemctl is-active --quiet mysql; then
        print_warning "MySQL服务未运行，尝试启动..."
        sudo systemctl start mysql || {
            print_error "MySQL启动失败"
            exit 1
        }
    fi
    
    # 创建数据库和用户
    print_info "创建Nacos数据库..."
    mysql -u root -p << EOF
CREATE DATABASE IF NOT EXISTS ${MYSQL_DB} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS '${MYSQL_USER}'@'%' IDENTIFIED BY '${MYSQL_PASSWORD}';
GRANT ALL PRIVILEGES ON ${MYSQL_DB}.* TO '${MYSQL_USER}'@'%';
FLUSH PRIVILEGES;
EOF

    # 导入Nacos数据库脚本
    print_info "导入Nacos数据库脚本..."
    mysql -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DB < $NACOS_HOME/conf/nacos-mysql.sql
    
    print_info "数据库配置完成"
}

# 函数：配置Nacos
configure_nacos() {
    print_info "配置Nacos..."
    
    # 备份原配置
    cp $NACOS_HOME/conf/application.properties $NACOS_HOME/conf/application.properties.bak
    
    # 生成新配置
    cat > $NACOS_HOME/conf/application.properties << EOF
# Nacos 配置文件
# 服务器配置
server.contextPath=/nacos
server.servlet.contextPath=/nacos
server.port=8848

# 数据库配置
spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://${MYSQL_HOST}:${MYSQL_PORT}/${MYSQL_DB}?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai
db.user.0=${MYSQL_USER}
db.password.0=${MYSQL_PASSWORD}

# 集群配置
nacos.cmdb.dumpTaskInterval=3600
nacos.cmdb.eventTaskInterval=10
nacos.cmdb.labelTaskInterval=300
nacos.cmdb.loadDataAtStart=false

# 管理配置
management.endpoints.web.exposure.include=*

# 认证配置
nacos.core.auth.enabled=true
nacos.core.auth.default.token.expire.seconds=18000
nacos.core.auth.default.token.secret.key=PowerBankNacosSecretKey2024PowerBankNacosSecretKey2024
nacos.core.auth.caching.enabled=true

# 日志配置
nacos.logs.path=/var/log/nacos
EOF

    # 创建日志目录
    sudo mkdir -p /var/log/nacos
    sudo chown $USER:$USER /var/log/nacos
    
    print_info "Nacos配置完成"
}

# 函数：创建系统服务
create_systemd_service() {
    print_info "创建Nacos系统服务..."
    
    sudo tee /etc/systemd/system/nacos.service > /dev/null << EOF
[Unit]
Description=Nacos Server
After=network.target

[Service]
Type=forking
User=$USER
Group=$USER
ExecStart=$NACOS_HOME/bin/startup.sh -m standalone
ExecStop=$NACOS_HOME/bin/shutdown.sh
Restart=on-failure
RestartSec=30

[Install]
WantedBy=multi-user.target
EOF

    sudo systemctl daemon-reload
    sudo systemctl enable nacos
    
    print_info "系统服务创建完成"
}

# 函数：启动Nacos
start_nacos() {
    print_info "启动Nacos服务..."
    
    sudo systemctl start nacos
    
    # 等待服务启动
    print_info "等待Nacos启动..."
    sleep 10
    
    # 检查服务状态
    if sudo systemctl is-active --quiet nacos; then
        print_info "Nacos启动成功！"
        print_info "访问地址: http://localhost:8848/nacos"
        print_info "默认用户名/密码: nacos/nacos"
    else
        print_error "Nacos启动失败，请检查日志: sudo journalctl -u nacos"
        exit 1
    fi
}

# 函数：配置命名空间
setup_namespaces() {
    print_info "配置Nacos命名空间..."
    
    # 等待Nacos完全启动
    sleep 5
    
    # 创建开发环境命名空间
    curl -X POST "http://localhost:8848/nacos/v1/console/namespaces" \
         -d "customNamespaceId=powerbank-dev&namespaceName=PowerBank开发环境&namespaceDesc=PowerBank系统开发环境"
    
    # 创建测试环境命名空间
    curl -X POST "http://localhost:8848/nacos/v1/console/namespaces" \
         -d "customNamespaceId=powerbank-test&namespaceName=PowerBank测试环境&namespaceDesc=PowerBank系统测试环境"
    
    # 创建生产环境命名空间
    curl -X POST "http://localhost:8848/nacos/v1/console/namespaces" \
         -d "customNamespaceId=powerbank-prod&namespaceName=PowerBank生产环境&namespaceDesc=PowerBank系统生产环境"
    
    print_info "命名空间配置完成"
}

# 主函数
main() {
    echo -e "${GREEN}开始部署Nacos服务注册中心...${NC}"
    
    # 检查依赖
    check_command "wget"
    check_command "mysql"
    check_java
    
    # 执行部署步骤
    download_nacos
    install_nacos
    setup_database
    configure_nacos
    create_systemd_service
    start_nacos
    setup_namespaces
    
    echo -e "${GREEN}=== Nacos部署完成 ===${NC}"
    echo -e "${GREEN}访问地址: http://localhost:8848/nacos${NC}"
    echo -e "${GREEN}用户名: nacos${NC}"
    echo -e "${GREEN}密码: nacos${NC}"
    echo ""
    echo -e "${YELLOW}请记住修改默认密码！${NC}"
}

# 执行主函数
main "$@"